//
//  ECDFileDirectoryController.m
//  XTCloud
//
//  Created by QA on 16/9/20.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "ECDFileDirectoryController.h"
#import "MJRefresh.h"
#import "EnterpriseDiskFilerCell.h"
#import "UITableView+Custom.h"
#import "NSDictionary+DataFormat.h"

#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"
#import "ServiceConnect.h"

#import "FileSizeFormatHelper.h"
#import "FileTypeIcon.h"
#import "DownLoadHandle.h"
#import "PreviewFileHelper.h"

@interface ECDFileDirectoryController ()<UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *resultData;

@property (assign, nonatomic) NSInteger selType;
@property (assign, nonatomic) NSInteger val;

@end

@implementation ECDFileDirectoryController

- (void)getPassingParameter:(id)object
{
    if(!(object && [object isKindOfClass:[NSDictionary class]])) return;
    NSDictionary *mDictionary = object;
    NSString *title = [mDictionary objectFormatStringForKey:@"title"];
    self.selType = [mDictionary objectFormatIntegerForKey:@"selType"];
    self.val = [mDictionary objectFormatIntegerForKey:@"val"];
    
    self.title = title && title.length > 0 ? title : @"云盘文件";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    
    self.tableView.tableFooterView= [[UIView alloc] init];
    [self setupRefresh];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupRefresh
{
    //添加下拉加载数据
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView headerBeginRefreshing];
}

- (void)stopRefresh
{
    //移除下拉加载数据
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
}

#pragma mark 网络获取数据

- (void)getNetWorkExternalData
{
    //selType：1表示查询所有数据，val传递文件夹ID（顶层val默认为-1）
    //selType：2表示查询分类数据, val文件类型：0文档 1图片 2视频 3音频 10其他
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:@(self.selType) forKey:@"selType"];
    [model setValue:@(self.val) forKey:@"val"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_MobileNetDisk" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [self.tableView headerEndRefreshing];
        
        //显示数据处理
        [self.resultData removeAllObjects];
        if(result.resultArray && result.resultArray.count>0){
            [self.resultData addObjectsFromArray:result.resultArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView reloadData];
        } else {
            [self.tableView setTableViewNotDataDrawText:@"暂无文件" isShow:YES];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self errorInfoViewText:@"系统繁忙，稍后再试"];
    }];
    
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark 开始进入刷新状态

- (void)headerRereshing
{
    [self getNetWorkExternalData];
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.resultData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifierOne = @"EnterpriseDiskFilerCell";
    EnterpriseDiskFilerCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierOne];
    if (!cell)
        cell = [[EnterpriseDiskFilerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierOne];
    
    NSDictionary *mDictionary = [self.resultData objectAtIndex:indexPath.row];
    cell.titleLable.text = [mDictionary objectFormatStringForKey:@"名称"];
    cell.timeLable.text = [mDictionary objectFormatStringForKey:@"创建时间"];
    
    //图标设置
    NSInteger fileType = [mDictionary objectFormatIntegerForKey:@"文档类型"];
    if(fileType == -1){
        cell.iconImage.image = [UIImage imageNamed:@"folder"];
    } else {
        NSString *iconString = [mDictionary objectFormatStringForKey:@"文件路径"];
        cell.iconImage.image = [FileTypeIcon setFileTypeIcon:iconString];
    }
    
    //文件尺寸格式化
    NSString *fileSize = [mDictionary objectFormatStringForKey:@"文件大小"];
    fileSize = [FileSizeFormatHelper getFileSizeString:fileSize];
    cell.sizeLable.text = fileSize;
    
    //设置下载按钮
    cell.downButton.tag = indexPath.row;
    [cell.downButton addTarget:self action:@selector(downadJunctFile:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *mDictionary = [self.resultData objectAtIndex:indexPath.row];
    NSInteger fileType = [mDictionary objectFormatIntegerForKey:@"文档类型"];
    if(fileType == -1){
        NSString *title = [mDictionary objectFormatStringForKey:@"名称"];
        NSInteger typeID = [mDictionary objectFormatIntegerForKey:@"ID"];
        
        //selType：1表示查询所有数据，val传递文件夹ID（顶层val默认为-1）
        //selType：2表示查询分类数据, val文件类型：0文档 1图片 2视频 3音频 10其他
        NSMutableDictionary *mDictionary = [NSMutableDictionary dictionary];
        [mDictionary setObject:title forKey:@"title"];
        [mDictionary setObject:@1 forKey:@"selType"];
        [mDictionary setObject:@(typeID) forKey:@"val"];
        
        ECDFileDirectoryController *view = [[ECDFileDirectoryController alloc] initWithValue:mDictionary];
        [self.navigationController pushViewController:view animated:YES];
    } else {
        [self previewJunctFile:indexPath.row];
    }
    
}


#pragma mark Button Event

- (void)previewJunctFile:(NSInteger)index
{
    //预览文件
    NSDictionary *fileDictionary = [self.resultData objectAtIndex:index];
    NSString *fileName = [fileDictionary objectFormatStringForKey:@"名称"];
    NSString *filePath = [fileDictionary objectFormatStringForKey:@"文件路径"];
    
    //创建连接，预览文件
    PreviewFileHelper *preview = [[PreviewFileHelper alloc] init];
    [preview startPreviewExternalFile:filePath fileName:fileName];
}

- (void)downadJunctFile:(UIButton*)button
{
    //下载附件
    NSDictionary *fileDictionary = [self.resultData objectAtIndex:button.tag];
    NSString *fileName = [fileDictionary objectFormatStringForKey:@"名称"];
    NSString *filePath = [fileDictionary objectFormatStringForKey:@"文件路径"];
    
    //创建连接，下载文件
    DownLoadHandle *downLoad = [[DownLoadHandle alloc] init];
    [downLoad startDownExternalFile:filePath fileName:fileName];
}

@end
